import datetime
import json
import time

from alipay import AliPay
from django import http
from django.shortcuts import render
from django.views import View
from django.utils import timezone
from apps.payment.models import Payment, OrderInfo
from QQ_Music import settings
from apps.users.models import User
from utils.singer_album import pay_money
from utils.singer_detail import vip

from utils.views import LoginRequiredJSONMixin


class Payment_View(LoginRequiredJSONMixin,View):
    """支付页面"""
    def get(self, request):

        user_id = request.session.get('user_id')
        users = User.objects.filter(id=user_id)
        pay_users = OrderInfo.objects.filter(user_id=user_id)
        expire_time = ''
        now_time = ''
        if pay_users:
            for x in pay_users:
                create_time = x.create_time
                now_time = str(create_time)[0:10]
                expire_time = x.expire_time
        else:
            create_time = ''
            expire_time = ''
        # 获取VIP信息
        user_id = request.session.get('user_id')
        user_vip = vip(user_id)
        is_vip = OrderInfo.objects.filter(user_id=user_id)

        content = {
            'users_id': users,
            'expire_time': expire_time,
            'create_time': now_time,
            'user_vip': user_vip,
            'user_id': user_id,
            'is_vip': is_vip,
        }

        return render(request, 'pay.html', content)

    def post(self, request):
        """获取数据调用支付宝"""
        user_id = request.session.get('user_id')
        order_id = timezone.now().strftime('%Y%m%d%H%M%S') + '%09d' % user_id
        json_dict = json.loads(request.body.decode())
        count = json_dict.get('count')
        money = json_dict.get('money')
        sum = json_dict.get('sum')
        print(order_id, type(money))
        day = pay_money(count, money)
        now = datetime.datetime.now()
        pay_time = now + datetime.timedelta(days=day)

        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
            alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 生成登录支付宝连接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=sum,
            # pay_day=
            subject="QQ音乐%s" % order_id,
            return_url=settings.ALIPAY_RETURN_URL,
        )
        users = OrderInfo.objects.filter(user_id=user_id)
        if users:
            for x in users:
                expire_time = x.expire_time
                pay_time = expire_time + datetime.timedelta(days=day)
                users.update(expire_time=pay_time)
        else:
            OrderInfo.objects.create(order_id=order_id,
                                     total_amount=sum,
                                     total_count=count,
                                     user_id=user_id,
                                     expire_time=pay_time)

        alipay_url = settings.ALIPAY_URL + "?" + order_string

        return http.JsonResponse({'errno': 0, 'alipay_url': alipay_url})

class PaymentStatusView(View):
    """支付成功"""
    def get(self, request):
        # 获取前端传入的请求参数
        query_dict = request.GET
        data = query_dict.dict()
        # 获取并从请求参数中剔除signature
        signature = data.pop('sign')
        current_time = time.strftime('%Y.%m.%d %H:%M:%S', time.localtime(time.time()))
        # 创建支付宝支付对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=settings.APP_PRIVATE_KEY_PATH,
            alipay_public_key_path=settings.ALIPAY_PUBLIC_KEY_PATH,
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # 校验这个重定向是否是alipay重定向过来的
        success = alipay.verify(data, signature)
        if success:
            # 读取order_id
            order_id = data.get('out_trade_no')
            # 读取支付宝流水号
            trade_id = data.get('trade_no')
            total_amount = data.get('total_amount')

            # 保存Payment模型类数据
            # Payment.objects.create(
            #     order_id=order_id,
            #     trade_id=trade_id
            # )
            print('000000000000123123',order_id, trade_id, total_amount)
            # # 修改订单状态为待评价
            # OrderInfo.objects.filter(order_id=order_id)
            #
            # # 响应trade_id
            # 获取VIP信息
            user_id = request.session.get('user_id')
            user_vip = vip(user_id)
            is_vip = OrderInfo.objects.filter(user_id=user_id)

            context = {
                # 'trade_id': trade_id,
                'current_time': current_time,
                'user_vip': user_vip,
                'user_id': user_id,
                'is_vip': is_vip
            }
            return render(request, 'pay_success.html', context)
        else:
            # 订单支付失败，重定向到我的订单
            return http.HttpResponseForbidden('非法请求')
